﻿namespace Morning_4Feb2013
{
    using System;
    using System.Numerics;

    class GreedyDwarf
    {
        // 1.3.2.1.02. http://bgcoder.com/Contests/Practice/Index/52#1

        static void Main()
        {
            string coooins = Console.ReadLine().Trim();
            long numPatterns = long.Parse(Console.ReadLine());
            string[] paaaatterns = new string[numPatterns];
            for (long i = 0; i < paaaatterns.GetLength(0); i++)
            {
                paaaatterns[i] = Console.ReadLine().Trim();
            }

            string[] coiiiins = coooins.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);

            long[] coins = new long[coiiiins.Length];
            for (long i = 0; i < coins.Length; i++)
            {
                coins[i] = long.Parse(coiiiins[i]);
            }

            long[][] patterns = new long[paaaatterns.Length][];
            for (long i = 0; i < patterns.GetLength(0); i++)
            {
                string[] rowPatterns = paaaatterns[i].Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
                long[] rowPatternsNums = new long[rowPatterns.Length];
                for (long j = 0; j < rowPatterns.Length; j++)
                {
                    rowPatternsNums[j] = long.Parse(rowPatterns[j]);
                }

                patterns[i] = rowPatternsNums;
            }

            // patterns[][] & coins[] are actual from now on

            long biggestPattern = long.MinValue;
            
            for (long i = 0; i < patterns.GetLength(0); i++)
            {
                long lastPosition = 0;
                bool[] positions = new bool[coins.Length];
                long tempPattern = 0;

                for (long j = 0; j < patterns[i].GetLength(0); j++)
                {
                    positions[lastPosition] = true;

                    tempPattern += coins[lastPosition];

                    lastPosition += patterns[i][j];

                    if (lastPosition >= coins.Length || lastPosition < 0)
                    {
                        break;
                    }

                    if (positions[lastPosition] == true)
                    {
                        break;
                    }

                    if (j == (long)(patterns[i].Length) - 1L)
                    {
                        j = -1;
                    }
                }

                if (tempPattern > biggestPattern)
                {
                    biggestPattern = tempPattern;
                }
            }

            Console.WriteLine(biggestPattern);
        }
    }
}